package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@Component
public class AliOSSUtils {
        private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        private String accessKeyId = "LTAI5tKxnhvu7UVyTWDBxr1w";
        private String accessKeySecret = "3OqjgHya7ZNioLTAQ9mOXktdaS8kfU";
        private String bucketName = "xder-dianping";

        /**
         * 实现上传图片到OSS
         */
        public String upload(MultipartFile file) throws IOException {
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();

            // 避免文件覆盖
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

            //上传文件到 OSS
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, inputStream);

            //
            String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

            ossClient.shutdown();
            return url;
        }
}
